package cn.fz.learn02.exception;

import cn.fz.learn02.domain.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        log.error("异常信息：{}", e.getMessage());
        return Result.error("接口异常:"+e.getMessage());
    }

    /**
     * 当请求超过设置的超时时间，会抛出AsyncRequestTimeoutException异常，
     * 这里直接用@ControllerAdvice全局捕获统一返回即可，前端获取约定好的状态码后再次发起长轮询请求，如此往复调用。
     */
    @ResponseStatus(HttpStatus.NOT_MODIFIED)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> bindExceptionHandler(MethodArgumentNotValidException e) {
        log.error("校验参数异常信息：{}", e.getMessage());
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Result.error(message);
    }

    @ExceptionHandler(AsyncRequestTimeoutException.class)
    public String asyncRequestTimeoutHandler(AsyncRequestTimeoutException e){
        System.out.println("异步请求超时");
        return "304";
    }
}
